package com.zm.tools.util.core;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zoum
 * @create 2018/6/11 13:25
 */
public class TableMetadateReadUtil {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private final static Logger LOGGER = LoggerFactory.getLogger(TableMetadateReadUtil.class);

    public TableMetadateReadUtil(){

    }

//    public TableMetadateReadUtil(File file){
//        PropertiesConfigUtil
//    }

    public Connection getConnection(){
        Connection conn = null;
        try {
            Class.forName(driverClassName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            LOGGER.error("数据库连接异常, ", e);
        } catch (SQLException e) {
            LOGGER.error("数据库连接异常, ", e);
        }
        return conn;
    }

    public List<String> getColumns(String tableName){
        Connection conn=getConnection();
        String sql="select * from " + tableName + " limit 1";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<String> columns = new ArrayList<>();
        try {
            stmt = conn.prepareStatement(sql);
            rs =stmt.executeQuery(sql);
            ResultSetMetaData data=rs.getMetaData();
            while(data.getColumnCount() > 0){
                for(int i = 1 ; i<= data.getColumnCount() ; i++){
                    columns.add(data.getColumnName(i));
                }
                break;
            }
            LOGGER.info("table is {}, columns is {}" , tableName, JSONObject.toJSONString(columns));
            return columns;
        } catch (SQLException e) {
            LOGGER.error("数据库操作异常, ", e);
        }finally {
            try {
                if (rs != null){
                    rs.close();
                }
                if (stmt != null){
                    stmt.close();
                }
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException e){
                LOGGER.error("数据库关闭异常, ", e);
            }
        }
        return null;
    }

    public List<Map<String, String>> getColumnsInfo(String tableName){
        Connection conn=getConnection();
        String sql="select * from " + tableName + " limit 1";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<Map<String, String>> columns = new ArrayList<>();
        try {
            stmt = conn.prepareStatement(sql);
            rs =stmt.executeQuery(sql);
            ResultSetMetaData data=rs.getMetaData();
            while(data.getColumnCount() > 0){
                for(int i = 1 ; i<= data.getColumnCount() ; i++){
                    Map<String, String> c= new HashMap<>();
                    c.put("fieldName", data.getColumnName(i));
                    String[]ary = data.getColumnClassName(i).split("\\.");
                    if (ary[ary.length-1].equals("Timestamp")){
                        c.put("fieldType", "Date");
                    }else {
                        c.put("fieldType", ary[ary.length-1]);
                    }

                    String columnClassName = data.getColumnClassName(i);
                    if (Objects.equals(columnClassName, "java.sql.Timestamp")){
                        c.put("imports", "java.util.Date");
                    }else if (!columnClassName.contains("java.lang.")){
                        c.put("imports", data.getColumnClassName(i));
                    }
                    columns.add(c);
                }
                break;
            }
            LOGGER.info("table is {}, columns is {}" , tableName, JSONObject.toJSONString(columns));
            return columns;
        } catch (SQLException e) {
            LOGGER.error("数据库操作异常, ", e);
        }finally {
            try {
                if (rs != null){
                    rs.close();
                }
                if (stmt != null){
                    stmt.close();
                }
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException e){
                LOGGER.error("数据库关闭异常, ", e);
            }
        }
        return null;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
